<template>
  <div class="index">
    <!-- 搜索 -->
    <van-nav-bar fixed placeholder class="index-navbar">
      <van-button slot="title" icon="search" plain type="info" to="search">搜索</van-button>
    </van-nav-bar>
    <!-- 推荐频道 -->
    <van-tabs sticky :offset-top="46" v-model="active">
      <!-- 频道中每一个标签 -->
      <van-tab v-for="(item,index) in userChannels" :key="index" :title="item.name">
        <van-pull-refresh v-model="isRefresh" @refresh="onRefresh">
          <van-list
            v-model="vanList.loading"
            :finished="vanList.finished"
            :offset="vanList.offset"
            :loading-text="vanList.loadingText"
            :finished-text="vanList.finishedText"
            @load="getArticles"
          >
            <van-cell
              v-for="(item,index) in articles[channelId]"
              :key="index"
              :title="item.title"
              :to="'/content/' + item.art_id"
            >
              <!-- 右边默认插槽中放一张图片 -->
              <img
                v-if="item.cover.type == 1"
                width="100"
                height="100"
                v-lazy="item.cover.images[0]"
              />
              <!-- label 插槽：下面的地方 -->
              <div slot="label">
                <div class="index-article-images" v-if="item.cover.type==3">
                  <img
                    v-for="(item1, index1) in item.cover.images"
                    :key="index1"
                    width="100"
                    height="100"
                    fit="cover"
                    :src="item1"
                    v-lazy="item1"
                  />
                </div>
                <p class="index-article-label">
                  <van-tag v-if="item.is_top==1" plain type="danger">置顶</van-tag>
                  <span>{{item.aut_name}}</span>
                  <span>{{item.comm_count}}评论</span>
                  <span>{{item.pubdate | relativeTime}}</span>
                </p>
              </div>
            </van-cell>
          </van-list>
        </van-pull-refresh>
      </van-tab>
      <!-- 按钮 -->
      <van-button @click="showPopup=true" slot="nav-right" icon="wap-nav" />
      <van-button
        @click="showPopup=true"
        style="position: fixed;right: 0"
        slot="nav-right"
        icon="wap-nav"
      />
    </van-tabs>
    <!-- 编辑频道 -->
    <van-popup
      close-icon-position="top-left"
      :overlay="false"
      closeable
      position="bottom"
      v-model="showPopup"
    >
      <!-- 我的频道 -->
      <van-cell-group :border="false">
        <!-- 自定义标题 -->
        <div slot="title">
          <van-button
            style="float:right"
            plain
            type="danger"
            size="mini"
            @click="showDeleteBtn = !showDeleteBtn"
          >{{showDeleteBtn?"完成":"编辑"}}</van-button>
          <h3>我的频道</h3>
        </div>
        <van-grid class="index-channel" :gutter="10">
          <van-grid-item
            v-for="(item, index) in userChannels"
            :key="index"
            :icon="showDeleteBtn?'close':''"
            :text="item.name"
            @click="onDeleteChannel($event,index)"
          />
        </van-grid>
      </van-cell-group>
      <!-- 推荐频道 -->
      <van-cell-group class="index-channel" :border="false">
        <!-- 自定义标题 -->
        <h3 slot="title">推荐频道</h3>
        <van-grid :gutter="10">
          <van-grid-item
            v-for="(item, index) in recommendChannels"
            :key="index"
            :text="item.name"
            @click="onAllChannelClicked(index)"
          />
        </van-grid>
      </van-cell-group>
    </van-popup>
  </div>
</template>

<script>
import {
  getAllChannels,
  getUserChannels,
  addUserChannel,
  deleteUserChannel,
  getChannelArticles
} from '@/utils/api.js'
export default {
  data () {
    return {
      isRefresh: false, // 是否正在刷新
      vanList: {
        loading: false, // 是否正在加载数据
        finished: false, // 是否已经完全加载完
        offset: 300, // 滚动条距离底部的距离
        loadingText: '加载中...', // 加载时文本
        finishedText: '没有更多了...' // 加载完之后文本
      },
      preTimestamp: {}, // 保存每个频道用来翻页的时间戳，频道ID做为键
      articles: {}, // 文章数据对象
      channelId: '', // 当前选中的频道的ID
      value: '',
      active: 0,
      channels: [], // 频道数据
      showPopup: false, // 是否显示编辑频道的层
      showDeleteBtn: false,
      userChannels: [] // 频道选择的频道
    }
  },
  // created： 获取页面中初始数据~~~
  async created () {
    const [r1, r2] = await Promise.all([getAllChannels(), getUserChannels()])
    this.channels = r1.data.data.channels
    this.userChannels = r2.data.data.channels
    // 更新当前频道的id
    this.channelId = this.userChannels[this.active].id
  },
  methods: {
    // 删除我的频道
    async onDeleteChannel (e, index) {
      // 判断点击的是否是关闭图标
      if (e.srcElement.nodeName === 'I') {
        // 从我的频道数组中截取出要删除的频道
        const data = this.userChannels.splice(index, 1)
        // 把截取处理的频道放到所有频道的数组中
        this.recommendChannels.push(data[0])
        // 调用删除接口
        try {
          await deleteUserChannel(data[0].id)
        } catch (error) {
          this.$toast.fail('删除频道失败！')
        }
      }
    },
    // 添加频道
    async onAllChannelClicked (index) {
      // 从所有频道的数组中截取出点击的频道
      const data = this.recommendChannels.splice(index, 1)
      // 把截取出来的频道放到我的频道数组中
      this.userChannels.push(data[0])

      // 调用服务器接口修改数据
      try {
        const params = {
          channels: [
            {
              id: data[0].id,
              seq: data[0].id
            }
          ]
        }
        await addUserChannel(params)
      } catch (error) {
        this.$toast.fail('添加频道失败！')
      }
    },
    // 获取文章数据
    async getArticles () {
      if (this.channelId !== '') {
        try {
          // 设置为当前正在加载数据的状态
          this.vanList.loading = true
          // 根据频道ID和上次时间戳加载数据
          const ret = await getChannelArticles(
            this.channelId,
            this.preTimestamp[this.channelId] || Date.now()
          )

          // 设置当前的状态不是 “正在加载”
          this.vanList.loading = false

          // 判断是否已经没有下一页了
          if (ret.data.data.results.length === 0) {
            // 设置已经加载完的状态
            this.vanList.loading = true
          } else {
            // 如果这个频道ID中还没有数据直接设置为当前数据
            if (this.articles[this.channelId] === undefined) {
              this.articles[this.channelId] = ret.data.data.results
            } else {
              // 把新的数据“展开” 然后放到原数组最后
              this.articles[this.channelId].push(...ret.data.data.results)
            }
            // 保存本次接口的时间戳数据，用来下次调用接口时的翻页
            this.preTimestamp[this.channelId] = ret.data.data.pre_timestamp
          }
        } catch (error) {
          this.$toast.fail('获取频道文章失败！')
        }
      } else {
        setTimeout(this.getArticles, 500)
      }
    },
    // 下拉刷新
    async onRefresh () {
      // 先清空当前这个频道的数据
      this.articles[this.channelId] = []
      // 设置翻页时间戳为最新的
      this.preTimestamp[this.channelId] = Date.now()
      // 重新调用接口获取当前的数据
      await this.getArticles()
      // 设置已经刷新完了
      this.isRefresh = false
    }
  },
  computed: {
    recommendChannels () {
      return this.channels.filter(item => {
        return !this.userChannels.find(userItem => userItem.id === item.id)
      })
    }
  },
  // 监听器
  watch: {
    // 监听 active 变量当值改变时调用函数
    active: async function (newValue, oldValue) {
      // 更新频道ID
      this.channelId = this.userChannels[newValue].id
      //
      if (this.articles[this.channelId] === undefined) {
        // 获取文章
        await this.getArticles()
      }
    }
  }
}
</script>

<style lang="less">
.index-navbar {
  .van-nav-bar__title {
    height: 80%;
    border-radius: 50px;
    width: 90%;
    background-color: rgba(255, 255, 255, 0.2);
  }
  .van-button {
    background-color: rgba(255, 255, 255, 0.2);
    width: 100%;
    height: 100%;
    &__icon {
      color: white !important;
    }
    &__text {
      font-weight: normal;
      color: white;
    }
  }
  // .van-tabs__wrap {
  //   padding-right: 50px;
  // }
}

.index {
  .van-popup {
    height: 100%;
    padding: 60px 10px 10px;
    box-sizing: border-box;
  }
}

.index-channel {
  .van-icon {
    position: absolute;
    right: -8px;
    top: -8px;
    font-size: 20px;
    z-index: 9999;
    background-color: #fff;
    color: #bbb;
  }
  .van-grid-item__text {
    margin-top: 0px !important;
  }
}
.index-article-images {
  display: flex;
  justify-content: space-between;
}
.index-article-label {
  span {
    margin-right: 20px;
  }
}
</style>
